from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db
import os

from html import CheckBox, DropDown, MultiSelect, RadioButton #importing the html wrappers.
import validate #import validation
import tables
import main
import datetime
import staticInits 
import cgi #for escaping html chars in forms
import re

class Instructor(object):
    """
    Class helps with hard coding of table for this first iteration. Will probably be removed in 
    future iterations when google data store is used.
    """
    def __init__(self, firstName, lastName, eid):
        "Obvious constructor."
        self.firstName = firstName
        self.lastName = lastName
        self.eid = eid


class addInstructor(webapp.RequestHandler):
    """
    This class deals with the admin add classes view.
    """

    
    def __init__(self):
        webapp.RequestHandler.__init__(self) #parent constructor call
        

        #DB CALLS
        self.instructors1 = []
        
        #building dictionaries, keyed with name attributes which are gauranteed unique to each entry
        for row in db.GqlQuery("SELECT * FROM Instructor"): self.instructors1.append(Instructor(row.firstName, row.lastName, row.eid))     

        
    def get(self):
        """
        Calls renderTemplate() for this class.
        """
        self.notValidated = dict()
        self.renderTemplate()

    def post(self):
        """
        Calls renderTemplate() for this class.
        """

        self.notValidated = dict()
        self.notValidated['fName'] = ""
        self.notValidated['lName'] = ""
        self.notValidated['eid'] = ""


        clicked = self.request.get('submit', default_value="default")
            
        # adds this instructor to datastore and immediately displays it in instructor list
        if clicked == 'Add Instructor' :
            fName = self.request.get('firstName')
            lName = self.request.get('lastName')
            eid = self.request.get('eid').lower()
            vFName = validate.validateFirstName(fName)
            vLName = validate.validateLastName(lName)
            vEid = validate.validateEid(eid)
            unique = validate.validateUniqueEid( eid ) and validate.validateUniqueInstructor( fName, lName )
            if vFName and vLName and vEid and unique:
                newInstructor = tables.Instructor( firstName = fName, lastName = lName, eid = eid )
                newInstructor.put()
                self.instructors1.append(Instructor(fName, lName, eid))
            else :
                if not vFName :
                    self.notValidated['fName'] = fName
                    self.notValidated['lName'] = lName
                    self.notValidated['eid'] = eid
                    self.response.out.write('<br><font color="red">Please enter a valid first name.</font><br />')
            
                if not vLName :
                    self.notValidated['fName'] = fName
                    self.notValidated['lName'] = lName
                    self.notValidated['eid'] = eid
                    self.response.out.write('<br><font color="red">Please enter a valid last name.</font><br />')
                if not vEid :
                    self.notValidated['fName'] = fName
                    self.notValidated['lName'] = lName
                    self.notValidated['eid'] = eid
                    self.response.out.write('<br><font color="red">Please enter a valid EID.</font><br />')
                if not unique :
                    self.notValidated['fName'] = fName
                    self.notValidated['lName'] = lName
                    self.notValidated['eid'] = eid
                    self.response.out.write('<br><font color="red">The instructor you have entered is already in the system, or this EID is already used by another instructor or student. Please enter an instructor with a unique EID and name. </font><br />')

            
        self.__init__()
        self.renderTemplate()
    
    def renderTemplate(self, addValid = "") :
        """
        Renders the Template setup.html for this class.
        """

        self.instructors1.sort(key = lambda x : x.lastName.lower() )
        
        #setting up template dictionary
        templateValues = {
            #'table' : table
            'instructors1' : self.instructors1,
            'badFName' : self.notValidated['fName'] if 'fName' in self.notValidated else "",
            'badLName' : self.notValidated['lName'] if 'lName' in self.notValidated else "",
            'badEid' : self.notValidated['eid'] if 'eid' in self.notValidated else "",

            }


        #telling it to use the template
        path = os.path.join(os.path.dirname(__file__), 'addInstructor.html')
        self.response.out.write(template.render(path, templateValues))



application = webapp.WSGIApplication([('/admin/addInstructor', addInstructor)], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

